import { css } from "@emotion/css";
import {
  Breadcrumb,
  Button,
  Form,
  Input,
  Message,
  Modal,
  Popconfirm,
  Space,
  Table,
  Tag,
  Tooltip,
} from "@arco-design/web-react";
import { usePagination } from "../../hooks/usePagination.ts";
import { useAPI } from "../../hooks/useAPI.ts";
import { useQuery } from "react-query";
import { useState } from "react";
import { Link } from "../../components/Link";
import {
  Role,
  SearchUserParams,
  SystemUserDataRow,
} from "../../api/types/system-user.ts";
import { RadarStatus } from "../../api/types/radar.ts";

import { useAsyncFn, useDebounce } from "react-use";
import {
  IconDelete,
  IconEdit,
  IconRefresh,
  IconRight,
  IconUserAdd,
} from "@arco-design/web-react/icon";
import { CameraStatus } from "../../api/types/camera.ts";
import { CameraColorMap, CameraTextMap } from "../../hooks/useCameraStatus.ts";
import { BindElderAndRoomModal } from "../../components/BindElderAndRoomModal";
import { useNavigate } from "react-router-dom";
import { EditUserInfoModal } from "../../components/EditUserInfoModal";
import { Icon } from "@iconify/react";
import { findRisk } from "../../components/ElderReport/ActivityListAndRecord.tsx";
import { BuildingAdminModal } from "../../components/BuildingAdminModal";
import { radarColorMap } from "../../hooks/useRadarStatus.ts";

export const bed = {
  "0": "左床",
  "1": "中床",
  "2": "右床",
};

const risk = {
  normal: "无风险",
  warning: "中风险",
  danger: "高风险",
};

const riskOrder = {
  normal: 0,
  warning: 1,
  danger: 2,
};

enum ElderOrBuilding {
  elder = "elder",
  building = "building",
}
export default function ElderManagement() {
  const api = useAPI();
  const navi = useNavigate();

  const { pagination, pageNum, pageSize, setTotal, resetPage } =
    usePagination();
  const [formRef] = Form.useForm<SearchUserParams>();
  const [, setUserId] = useState<number>();
  const [userData, setUserData] = useState<SystemUserDataRow | null>();
  const [searchValues, setSearchValues] = useState<SearchUserParams | null>(
    null
  );

  const params: SearchUserParams = {
    pageNum,
    pageSize,
    roleIds: Role.ElderUser,
  };

  const { data, isLoading, refetch } = useQuery(
    ["query-system-user-list", params],
    async () => {
      try {
        const values = searchValues || { key: "" };
        const response = await api.getSystemUserList_({
          ...values,
          ...params,
          roleIds: 2,
        });
        setTotal(response.data?.data.total || 0);

        return response.data?.data.rows.map((row: any, index: number) => ({
          index: index + 1 + (pageNum - 1) * pageSize, // Add index starting from 1
          ...row,
        }));
      } catch (error) {
        if (error instanceof Error) {
          Message.error(error.message);
        } else {
          Message.error("操作失败，请稍后重试");
        }
      }
    },
    // {
    //   onSuccess: (data) => {
    //     console.log(data);
    //     setTotal(data?.length || 0);
    //   },
    // }
  );

  const unBindRoom = async (userId: any, userName: any) => {
    if (!userName && !userId) Message.error("信息不全");
    try {
      await api.updateSystemUser({
        buildingId: null,
        userName: userName,
        userId,
        roleIds: [Role.ElderUser],
      });
      Message.success("解绑成功");
      refetch();
    } catch {
      Message.error("解绑失败");
    }
  };

  const [, onSearch] = useAsyncFn(async (values: SearchUserParams) => {
    resetPage();
    setSearchValues(values);
    await refetch();
  });
  useDebounce(
    () => {
      onSearch(searchValues as SearchUserParams);
    },
    300,
    [searchValues]
  );
  const [isOpenAddElderAndRoomModal, setIsOpenElderAndRoomModal] =
    useState(false);
  const [isOpenUpdateUserModal, setIsOpenUpdateUserModal] = useState(false);
  const [, setIsOpenElderModal] = useState(false);
  const [isOpenAddUserModal, setIsOpenAddUserModal] = useState(false);
  const [isOpenQuestionModal, setIsOpenQuestionModal] = useState(false);
  const [addElderOrBuilding, setAddElderOrBuilding] = useState<ElderOrBuilding>(
    ElderOrBuilding.elder
  );

  return (
    <div>
      {isOpenUpdateUserModal && (
        <EditUserInfoModal
          visible={isOpenUpdateUserModal}
          defaultData={userData}
          onClose={() => {
            setIsOpenUpdateUserModal(false);
            setUserData(null);
          }}
          title="编辑长辈信息"
          isEdit={true}
          isEditBuilding={true}
          isEditElder={true}
          onSuccess={() => {
            setIsOpenUpdateUserModal(false);
            refetch();
          }}
        />
      )}

      <BuildingAdminModal
        visible={isOpenAddUserModal}
        onClose={() => {
          setIsOpenAddUserModal(false);
        }}
        title="添加长辈信息"
        onSuccess={() => {
          setIsOpenAddUserModal(false);
          refetch();
        }}
      />

      <BindElderAndRoomModal
        visible={isOpenAddElderAndRoomModal}
        onClose={() => {
          setUserData(null);
          setIsOpenElderAndRoomModal(false);
        }}
        onSuccess={async () => {
          setIsOpenElderAndRoomModal(false);
          refetch();
        }}
        onAddElder={() => {
          setAddElderOrBuilding(ElderOrBuilding.elder);
          setIsOpenQuestionModal(true);
        }}
        onAddBuilding={() => {
          setAddElderOrBuilding(ElderOrBuilding.building);
          setIsOpenQuestionModal(true);
        }}
        title="绑定长辈与房间"
        defaultData={userData}
      />

      <Modal
        title={
          addElderOrBuilding === ElderOrBuilding.elder
            ? "用户不存在!"
            : "楼栋不存在"
        }
        visible={isOpenQuestionModal}
        onOk={() => {
          if (addElderOrBuilding === ElderOrBuilding.elder) {
            setIsOpenElderModal(true);
          } else {
            navi("/buildingManagement/addBuilding");
          }
        }}
        onCancel={() => setIsOpenQuestionModal(false)}
        autoFocus={false}
        focusLock={true}
      >
        <p>
          {addElderOrBuilding === ElderOrBuilding.elder
            ? "是否要添加新用户?"
            : "是否要添加新楼栋?"}
        </p>
      </Modal>

      <Breadcrumb
        className={css`
          padding: 12px;
          border-radius: 1px;
          font-weight: bold;
          border-left: 5px solid rgb(var(--primary-6));
          margin-bottom: 20px;
        `}
        separator={<IconRight />}
      >
        <Breadcrumb.Item style={{ fontWeight: 400 }}>
          <Link
            to="/homepage/seniorManagement"
            style={{
              textDecoration: "none",
              transition: "color 0.3s",
              fontWeight: "bold",
              fontSize: "15px",
            }}
          >
            长辈管理
          </Link>
        </Breadcrumb.Item>
      </Breadcrumb>

      <div
        className={css`
          width: 100%;
          display: flex;
          justify-content: space-between;
          align-items: center;
        `}
      >
        <Form
          form={formRef}
          onSubmit={onSearch}
          layout="inline"
          className={css``}
        >
          <Form.Item field="key" label="搜索：">
            <Input.Search
              value={searchValues?.key}
              onChange={(v) => {
                setSearchValues({ ...searchValues, key: v });
              }}
              placeholder="请输入关键字"
              style={{ width: "200px" }}
            />
          </Form.Item>
          <Form.Item>
            <Button
              type="outline"
              htmlType="button"
              onClick={() => {
                formRef.resetFields();
                onSearch(formRef.getFieldsValue() as SearchUserParams);
                setSearchValues({ ...searchValues, key: "" });
                refetch();
              }}
            >
              <IconRefresh />
              重置
            </Button>
          </Form.Item>
        </Form>
        <Button
          type="primary"
          size="small"
          className={css`
            margin-right: 10px;
          `}
          onClick={(e) => {
            e.preventDefault();
            setIsOpenAddUserModal(true);
          }}
        >
          <IconUserAdd />
          创建新长辈
        </Button>
        <Button
          type="primary"
          size="small"
          onClick={(e) => {
            e.preventDefault();
            setUserData(null);
            setIsOpenElderAndRoomModal(true);
          }}
        >
          <Icon icon="tabler:link" /> 绑定长辈与房间
        </Button>
      </div>
      <Table
        data={data}
        loading={isLoading}
        pagination={pagination}
        rowKey="userId"
        className={css`
          margin-top: 16px;
        `}
        columns={[
          {
            title: "序号",
            dataIndex: "index",
            key: "index",
            align: "center", // Center the cell content
            headerAlign: "center", // Center the header content
            sorter: (a, b) => a.index - b.index,
          },
          {
            title: "长辈名称",
            dataIndex: "nickName",
            key: "nickName",
            align: "center", // Center the cell content
            headerAlign: "center", // Center the header content
          },
          {
            title: "居住位置",
            dataIndex: "buildingName",
            key: "buildingName",
            align: "center", // Center the cell content
            headerAlign: "center", // Center the header content
            render: (buildingName, row) =>
              buildingName === null
                ? "未绑定"
                : `${buildingName}-${row.floorName}-${row.roomName}${
                    row.location
                      ? "-" + bed[row.location as keyof typeof bed]
                      : ""
                  }`,
          },
          {
            title: "风险等级",
            dataIndex: "riskLevel",
            key: "riskLevel",
            align: "center", // Center the cell content
            headerAlign: "center", // Center the header content
            render: (riskLevel) => findRisk(riskLevel),
            sorter: (a, b) =>
              riskOrder[a.riskLevel as keyof typeof risk] -
              riskOrder[b.riskLevel as keyof typeof risk],
          },
          {
            title: "摄像头信息",
            dataIndex: "cameraStatus",
            key: "cameraStatus",
            align: "center", // Center the cell content
            headerAlign: "center", // Center the header content
            render: (record: CameraStatus, row) =>
              record ? (
                <Tag color={CameraColorMap[record]}>
                  D{row.channel}({CameraTextMap[record]})
                </Tag>
              ) : (
                ""
              ),
          },
          {
            title: "雷达信息",
            dataIndex: "radarStatus",
            key: "radarStatus",
            align: "center", // Center the cell content
            headerAlign: "center", // Center the header content
            render: (record: CameraStatus, row) =>
              record ? (
                <Tag color={CameraColorMap[record]}>
                  {row.radarName}({CameraTextMap[record]})
                </Tag>
              ) : (
                ""
              ),
          },
          {
            title: "ai系统状态",
            dataIndex: "aiStatus",
            key: "aiStatus",
            align: "center", // Center the cell content
            headerAlign: "center", // Center the header content
            render: (record: RadarStatus) => (
              <Tag color={radarColorMap[record]}>
                {record == 1 ? "在线" : "离线"}
              </Tag>
            ),
          },
          {
            title: "操作",
            dataIndex: "userId",
            key: "userId",
            align: "center", // Center the cell content
            headerAlign: "center", // Center the header content
            render: (record, row) => (
              <Space>
                <Tooltip content="编辑">
                  <Button
                    size="small"
                    shape="circle"
                    type="outline"
                    icon={<IconEdit />}
                    onClick={(e) => {
                      e.preventDefault();
                      setUserId(record);
                      setUserData(row);
                      setIsOpenUpdateUserModal(true);
                    }}
                  />
                </Tooltip>
                {row.buildingId !== null ? (
                  <Popconfirm
                    focusLock
                    title="请确认"
                    content={
                      <p>
                        {`解绑${row.nickName}与房间`}
                        <br />
                        {`${row.buildingName}-${row.floorName}-${row.roomName}？`}
                      </p>
                    }
                    onOk={async () => {
                      setUserId(record);
                      setUserData(row);
                      await unBindRoom(record, row.userName);
                    }}
                  >
                    <Tooltip content="解绑">
                      <Button
                        size="small"
                        shape="round"
                        type="outline"
                        icon={<Icon icon="tabler:link-off" />}
                      />
                    </Tooltip>
                  </Popconfirm>
                ) : (
                  <Tooltip content="绑定房间">
                    <Button
                      size="small"
                      shape="round"
                      type="outline"
                      icon={<Icon icon="tabler:link" />}
                      onClick={(e) => {
                        e.preventDefault();
                        setUserId(record);
                        setUserData(row);
                        setIsOpenElderAndRoomModal(true);
                      }}
                    />
                  </Tooltip>
                )}
                <Popconfirm
                  focusLock
                  title="请确认"
                  content="是否删除该长辈？"
                  onOk={async () => {
                    api
                      .deleteSystemUser(record)
                      .then(() => {
                        Message.success("删除成功");
                      })
                      .catch(() => {
                        Message.error("删除失败");
                      });
                    await refetch();
                  }}
                >
                  <Tooltip content="删除">
                    <Button
                      size="small"
                      shape="circle"
                      type="outline"
                      icon={<IconDelete />}
                    />
                  </Tooltip>
                </Popconfirm>
              </Space>
            ),
          },
        ]}
      />
    </div>
  );
}
